import { createRouter, createWebHistory } from "vue-router";

import SignUpPage from "@/pages/SignUpPage";
import Login from "@/pages/Login";
import Register from "@/pages/Register";
import ManagementPage from "@/pages/ManagementPage";
import MainPage from "@/pages/MainPage";
import ChangePassword from "@/pages/ChangePassword.vue";

const router = createRouter({
	history: createWebHistory(),
	routes: [
		{
			name: "index",
			path: "/",
			component: MainPage,
			meta: {
				isNeedLogin: true,
			},
		},
		{ name: "login", path: "/login", component: Login },
		{
			name: "register",
			path: "/register",
			component: Register,
			meta: {
				isNeedLogin: true,
				isNeedMaster: true,
			},
		},
		{
			name: "manage",
			path: "/manage",
			component: ManagementPage,
			meta: {
				isNeedLogin: true,
				isNeedMaster: true,
			},
		},
		{
			name: "bm",
			path: "/bm",
			component: SignUpPage,
			meta: {
				isNeedLogin: true,
			},
		},
		{
			name: "xgPass",
			path: "/changePass",
			component: ChangePassword,
			meta: {
				isNeedLogin: true,
			},
		},
	],
});

router.beforeEach((to, _, next) => {
	let user = JSON.parse(sessionStorage.getItem("user"));
	if (to.meta.isNeedLogin) {
		if (user) {
			if (to.meta.isNeedMaster) {
				if (user.isAdmin) next();
				else {
					next("/");
				}
			} else {
				if (!user.isAdmin) next();
				else {
					next("/manage");
				}
			}
		} else {
			next({ path: "/login" });
		}
	} else {
		next();
	}
});

export default router;
